<?php
class WebDataBlock extends Model{
	public $_table = 'block';
	// Import The Database
	public function addData(){
		$name = isset($_POST['name'])?(Character::HTMLToDbEncode($_POST['name'])):'';
		$count= isset($_POST['count'])?(intval($_POST['count'])):'';
		$arr = array(
			'`name`'=>"'{$name}'",
			'`num`'=>$count
		);
		return $this->add($arr);
	}

	// Update The Database
	public function updateData($id){
		$name = isset($_POST['name'])?(Character::HTMLToDbEncode($_POST['name'])):'';
		$count= isset($_POST['count'])?(intval($_POST['count'])):'';
		$arr = array(
			'name'=>$name,
			'num'=>$count
		);
		return $this->update($arr,'id='.$id);
	}
	/*Fetch a Data{{{
	 *@param $id one data from block table;
	 *@return Array
	 */
	public function getOneData($id){
		$sql = "select * from {$this->_table} where `id`=".intval($id);
		$data = $this->getOne($sql);
		return $data;
	}
	// }}}
	
	/*Update The Data By Id {{{
	 *@param $json 
	 *@param $id 
	 */
	public function updateJson($json,$id){
		$arr = array(
			'json'=>$json
		);
		$this->update($arr,'id='.$id);

		$this->updateHTML($id);
		Core::getInstance()->app_load_class('Relate')->syncTpl($id);
	}
	// }}}
	
	/*Update The Data's Tpl By Id {{{
	 *@param $html
	 *@param $id 
	 */
	public function updateTpl($tpl,$id){
		$arr = array(
			'tpl'=>Character::HTMLToDbEncode($tpl)
		);
		$this->update($arr,'id='.$id);

		$this->updateHTML($id);
		Core::getInstance()->app_load_class('Relate')->syncTpl($id);
	}
	// }}}
	

	/**
	 * Update the Data's HTML By Id
	 */
	public function updateHTML($id){
		$data = $this->getOneData($id);
		if(empty($data)){
			Core::showmessage('Json\'s data is Invalid!');
		}
		if(empty($data['tpl'])) return false;

		$tpl = Character::HTMLToDbDecode($data['tpl']);
		$tmp_tpl = WEB_ROOT.'tmp/'.'tmp.php';

		ob_start();
		file_put_contents($tmp_tpl,$tpl);
		require_once $tmp_tpl;
		$html = ob_get_contents();
		ob_end_clean();

		$arr = array(
			'html'=>Character::HTMLToDbEncode($html)
		);
		$this->update($arr,'id='.$id);

	}

	public function delData($id){
		$this->del($id);
	}

}
